<?php
namespace App\Http\Controllers\User;

use App\Http\Controllers\BaseController;
use DB;
use App\Libraries\newsmsapi;
use App\Libraries\Captcha;
use Config;
use App\Http\Models\User;
use App\Http\Models\Total;
use Illuminate\Support\Facades\Cache;


class LoginController extends BaseController
{

    private $request;

   //图形验证有效期
    private $captcha_expire_time = 180;

    public function __construct()
    {

    }

    public function  test()
    {
        echo makeNickName();die;
    }


    //供应商注册
    public function sellerRegister(){
           $requestAll  = $this->requestAll();
            $request = $requestAll['formData'];
           $userInfo = $this->getUserInfo();

        //用户名验证
            $isUser = DB::table('user')->where('user_name',$request['user_name'])->first();
            if(!empty($isUser)){
                return $this->jsonResult(201,'','用户名已存在');
            }
           $data = [
               'user_name'=> isset($request['user_name'])?$request['user_name']:'',
               'user_pass'=>md5(md5($request['user_pass']).config('session.pass')),
               'company_name'=>isset($request['company_name'])?$request['company_name']:'',//公司名称
               'province_id'=>isset($request['province_id'])?$request['province_id']:0,
               'city_id'=>isset($request['city_id'])?$request['city_id']:0,
               'area_id'=>isset($request['area_id'])?$request['area_id']:0,
               'post_addr'=>isset($request['post_addr'])?$request['post_addr']:'',//通信地址
               'business_license_num'=>isset($request['business_license_num'])?$request['business_license_num']:'',//营业执照号
               'legal_person'=>isset($request['legal_person'])?$request['legal_person']:'',//法人姓名
               'legal_person_no'=>isset($request['legal_person_no'])?$request['legal_person_no']:'',//法人身份证号
               'user_email'=>isset($request['user_email'])?$request['user_email']:'',//邮箱
               'user_status'=>1,//待审核
               'user_type'=>11 //供应商
           ];

          $re = DB::table('user')->where('user_id',$userInfo['user_id'])->update($data);

          //供应商数量增加
          if($re>0){
              $total = new Total;
              $total->sellerRegisterTotal();
          }

        //1供应商经营许可证，2身份证正面，3反面4医疗器械经营许可证20医院经营许可证21医疗机构执业许可证
           $file = [
               ['file_user_id'=>$userInfo['user_id'],'file_type'=>1,'file_url'=>$request['yingyeImg'],'file_user_type'=>11],//营业执照扫描件 1
               ['file_user_id'=>$userInfo['user_id'],'file_type'=>2,'file_url'=>$request['zhengImg'],'file_user_type'=>11],//法定代表人身份证（正面） 2
               ['file_user_id'=>$userInfo['user_id'],'file_type'=>3,'file_url'=>$request['fanImg'],'file_user_type'=>11],//法定代表人身份证（反面） 3
               ['file_user_id'=>$userInfo['user_id'],'file_type'=>4,'file_url'=>$request['xvkeImg'],'file_user_type'=>11],//医疗器械经营许可证/第二类医疗器械经营备案证 4
               ['file_user_id'=>$userInfo['user_id'],'file_type'=>4,'file_url'=>isset($request['xvkeImg1'])?$request['xvkeImg1']:'','file_user_type'=>11],//医疗器械经营许可证/第二类医疗器械经营备案证 4

           ];
           $oldFile = DB::table('file')->where(['file_user_id'=>$userInfo['user_id'],'file_user_type'=>11])->get();
           if(!empty($oldFile)){
               DB::table('file')->where(['file_user_id'=>$userInfo['user_id'],'file_user_type'=>11])->update(['status'=>1]);
           }
           //插入图片
           DB::table('file')->insert($file);

           return $this->jsonResult(200);

    }

    //医院注册
    public function buyerRegister(){
        $requestAll  = $this->requestAll();
        $request = $requestAll['formData'];
        $userInfo = $this->getUserInfo();

        $hospitalType1 = Config::get("hospitaltype.hospital_type1");
        $hospitalType2 = Config::get("hospitaltype.hospital_type2");
        //用户名验证
        $isUser = DB::table('user')->where('user_name',$request['user_name'])->first();

        if(!empty($isUser)){
            return $this->jsonResult(201,'','用户名已存在');
        }
        //邀请码 验证
        if(!empty($request['invite_code'])){
            $user = DB::table('invite_code')->where('code',$request['invite_code'])->pluck('user_id')->toArray();

            if(!empty($user[0])){
                $invite_user_id = $user[0];

            }else{
                return $this->jsonResult(201,'','邀请码不正确或者已作废');

            }

        }

        $data = [
            'user_name'=>isset($request['user_name'])?$request['user_name']:'',
            'user_pass'=>md5(md5($request['user_pass']).config('session.pass')),
            'company_name'=>isset($request['company_name'])?$request['company_name']:'',//医院名称
            'agent'=>isset($request['agent'])?$request['agent']:'',//负责人
            'province_id'=>isset($request['province_id'])?$request['province_id']:0,
            'city_id'=>isset($request['city_id'])?$request['city_id']:0,
            'area_id'=>isset($request['area_id'])?$request['area_id']:0,
            'post_addr'=>isset($request['post_addr'])?$request['post_addr']:'',//通信地址
            'hospital_type1'=>isset($request['hospital_type1'])?$request['hospital_type1']:0,//医院类型1,
            'hospital_type2'=>isset($request['hospital_type2'])?$request['hospital_type2']:0,//医院类型2,
            'tax_register_num'=>isset($request['tax_register_num'])?$request['tax_register_num']:'',//税务登记号
            'user_status'=>1,//待审核
            'user_type'=>10, //医院采购方
            'invite_user_id'=>!empty($invite_user_id)?$invite_user_id:0

        ];


//        echo $hospitalType1[$request['hospital_type1']];
//        echo $hospitalType2[$request['hospital_type1']][$request['hospital_type2']];
//
//        die;

        $re = DB::table('user')->where('user_id',$userInfo['user_id'])->update($data);

        //添加推荐记录
        if($re > 0 && !empty($data['invite_user_id'])){
            DB::table('invite_list')->insertGetId(['invite_user_id'=>$data['invite_user_id'],'user_id'=>$userInfo['user_id'],'invite_code'=>$request['invite_code']]);
        }

        //营业执扫描件20，医疗机构执业许可证21
        $file = [
            ['file_user_id'=>$userInfo['user_id'],'file_type'=>20,'file_url'=>$request['yingyeImg'],'file_user_type'=>10],//营业执照扫描件 1
            ['file_user_id'=>$userInfo['user_id'],'file_type'=>21,'file_url'=>$request['zhiyeImg'],'file_user_type'=>10],//法定代表人身份证（正面） 2
        ];

        $oldFile = DB::table('file')->where(['file_user_id'=>$userInfo['user_id'],'file_user_type'=>10])->get();
        if(!empty($oldFile)){
            DB::table('file')->where(['file_user_id'=>$userInfo['user_id'],'file_user_type'=>10])->update(['status'=>1]);
        }
        DB::table('file')->insert($file);

        return $this->jsonResult(200);


    }


    //获取SessionKey
    public function getSessionKey(){
        $request  = $this->requestAll();


        $data = $this->getSessionKeyByCode($request);


        $this->jsonResult(200,$data,'');
    }




    //获取手机号，如果没有账号，创建账号，有过有关联手机返回关联手机号
    public function getUserPhone(){
        $request  = $this->requestAll();
        //获取手机号
        $data = $this->getPhoneByCode($request['encryptedData'],$request['iv'],$request['code']);
        /**
        {countryCode:"86",phoneNumber:"13341160629",purePhoneNumber:"13341160629"
         * ,watermark:{timestamp: 1530612457, appid: "wx86325a63a2d3e240"},openid:"opoaZ5V63yVXow4e5EVq7AwBdrzg"}
         **/
        //查看手机号是否已注册
        $userModel = new User();
        $re =$userModel->phoneRegister(array_merge($data,$request));
        $userInfo = array_merge($re,$data);


        //存入数据库，获取token
        unset($userInfo['watermark']);
        $token = $this->tokenForReids($userInfo);
        $userInfo['user_token'] = $token;
        $this->jsonResult(200,$userInfo,'');
    }

    //快捷登录 手机号登录注册
    public function phoneLogin(){

        $request  = $this->requestAll();
        $userModel = new User();

        //验证手机验证码
        $successTime = date('Y-m-d H:i:s',time()-60*5);
          $su = DB::table('sms')->where('phone',$request['user_phone'])->where('code',$request['code'])
                ->where('add_time','>',$successTime)->first();

        if(empty($su)){
            $this->jsonResult(201,'','验证码不正确，请重新发送');

        }

        $res  = DB::table('user')->where(['user_phone'=>$request['user_phone'],'is_del'=>0])->first();
        if(!empty($res)){

            $data['user_token'] =  $this->tokenForReids($res);
            $data['user_id'] =  $res['user_id'];
            $data['phoneNumber'] =  $res['user_phone'];
            $data['user_type'] =  $res['user_type'];
            $data['user_nickname'] =  $res['user_nickname'];


            $this->jsonResult(200,$data);
        }else{
            $userData =[
                'phoneNumber'=>$request['user_phone'],
                'openid'=>'',
                'user_nick'=>'',
            ];
            $re =$userModel->phoneRegister($userData);
            $data['user_id'] =  $re['user_id'];
            $data['phoneNumber'] =  $request['user_phone'];
            $data['user_type'] =  0;
            $data['user_token'] =  $this->tokenForReids($data);
            $data['user_nickname'] =  $re['user_nickname'];

            $this->jsonResult(200,$data);

        }

    }
    //发送短信
    function sendSmsCode() {
        $request  = $this->requestAll();
        $phone = $request['phone'];
        $is_phone = is_phone($phone);

        if($is_phone == 0){
            $this->jsonResult(1001);

        }
//        p($request);die;
        $re = $this->sendSms($phone);

        $this->jsonResult(200);

    }

    //通过token获取用户信息
    public function getUserInfoByToken(){
        $request  = $this->requestAll();
        $re = $this->getUserInfo($request);
        $re['region'] = [
            provinceDataMap($re['province_id']),
            cityDataMap($re['city_id']),
            areaDataMap($re['area_id'])
        ];
        $this->jsonResult(200,$re);
    }


    // token存入数据redis, $type， 0小程序
    public function tokenForReids($data, $type = 0,$time = ''){

        $info['user_id']         		= isset($data['user_id']) ? $data['user_id'] :0;
        $info['user_type']  		= isset($data['user_type'])? $data['user_type']:0;
        $info['user_phone']      		= isset($data['phone'])? $data['phone']:'';
        $info['user_email']  		= isset($data['user_email'])? $data['user_email']:'';
        $info['user_name']  		= isset($data['user_name'])?$data['user_name']:'';//用户名
        $info['company_name']     		= isset($data['company_name'])?$data['company_name']:0;
        $info['user_token']      		= isset($data['user_token']) ? $data['user_token'] :'';
        $info['login_type'] 		= $type;

        $token = $this->createToken();
        $redis = $this->redis();

        $redish = Config::get('key.redishkey');

        if (!empty($info['user_token'])) {
            $redis->hDel($redish,$info['user_token']);
        }

        $info['user_token'] = $token;
        $json = json_encode($info);
        //$redis->setex($token, $time, $json);
        $redis->hset($redish,$token,$json);
        return $token;
    }

    //生成token
    private function createToken()
    {
//        if ($this->mobile == '15810867923') {
//            return 'fa40aa9b10033591b85c76e03d3b489b';
//        }
        return md5(uniqid(rand()));
    }


    //验证登录
    public function checkLogin(){
        $request  = $this->requestAll();
        if(empty($request)){
            return false;
        }
        $date = date('Y-m-d H:i:s',strtotime("-20000 minute"));
        $data = DB::table('token')->where('key',$request['token'])->where('add_time','>',$date)->first();
        if(empty($data)){

            return false;
        }
    }

    //退出登录
    public function logout(){
        $request  = $this->requestAll();
        DB::table('token')->delete(['key'=>$request['token']]);

        $this->jsonResult(200);

    }

    //账号密码登录
    public function userLogin() {
        $request  = $this->requestAll();
        $userName =$request['user_name'];
        $pass = md5(md5($request['user_pass']).config('session.pass'));
        $res  = DB::table('user')
            ->where(['user_pass'=>$pass,'is_del'=>0])
            ->where(function($query) use($userName){
                $query->where('user_phone','=',$userName)
                    ->orWhere(function($query) use($userName){
                        $query->where('user_email','=',$userName);
                    })->orWhere(function($query) use($userName){
                        $query->where('user_name','=',$userName);
                    });
            })
            ->first();
        
        if(!empty($res)){

            $data['user_token'] =  $this->tokenForReids($res);
            $data['user_id'] =  $res['user_id'];
            $data['phoneNumber'] =  $res['user_phone'];
            $data['user_type'] =  $res['user_type'];
            $data['user_nickname'] =  $res['user_nickname'];


            $this->jsonResult(200,$data);
        }else{
            $this->jsonResult(201,'','账号或密码错误！');
        }
    }

    //修改密码
    public function editPass(){
        $request  = $this->requestAll();
        $userInfo = $this->getUserInfo();
        $code = $request['code'];
        $pass = md5(md5($request['user_pass']).config('session.pass'));

        $sms = DB::table('sms')->where(['code'=>$code,'is_use'=>0])->first();

        if(!empty($sms)){
            $re  = DB::table('user')->where('user_id',$userInfo['user_id'])
                ->update(['user_pass'=>$pass]);

            if($re >0){
                DB::table('sms')->where(['code'=>$code,'is_use'=>0])->update(['is_use'=>1]);

                $this->jsonResult(200,$re);
            }else{
                $this->jsonResult(201,'','新密码和原密码相同');
            }

        }


    }





}